package hongcaosp.app.android.user.settings.info;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.login.UserToken;
import hongcaosp.app.android.modle.DataCallBack;
import hongcaosp.app.android.modle.bean.UserInfo;
import hongcaosp.app.android.modle.bean.UserInfoWrap;
import hongcaosp.app.android.modle.impl.UserModleImpl;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import xlj.lib.android.base.component.BaseActivity;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.DateUtil;
import xlj.lib.android.base.utils.PictureSelectUtils;
import xlj.lib.android.base.utils.StatusBarUtil;

public class EditUserInfoActivity extends BaseActivity {

    private TextView tv_userNick,tv_userComment,tv_userSex,tv_userBirthday,tv_userLocality,tv_userSchool;
    private ImageView iv_userLogo;

    private final int REQUEST_CODE_CHOOSE = 66;
    private static final int PHOTO_REQUEST_CUT = 77;// 结果

    @Override
    protected void initData(Intent intent) {
        showUserInfo();
    }

    @Override
    protected void initView() {
        StatusBarUtil.setStatusBarDarkTheme(this,false);

        findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        iv_userLogo = findViewById(R.id.user_logo);
        tv_userNick = findViewById(R.id.user_nick);
        tv_userComment = findViewById(R.id.user_comment);
        tv_userSex = findViewById(R.id.user_sex);
        tv_userBirthday = findViewById(R.id.user_birthday);
        tv_userLocality = findViewById(R.id.user_locality);
        tv_userSchool = findViewById(R.id.user_school);

        findViewById(R.id.layout_logo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AndPermission.with(EditUserInfoActivity.this)
                        .runtime()
                        .permission(Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                ToastManager.getInstance().showToast("请给我权限");
                            }
                        })
                        .onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                Matisse.from(EditUserInfoActivity.this)
                                        .choose(MimeType.ofImage())
                                        .countable(true)
                                        .maxSelectable(1)
                                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                        .thumbnailScale(0.85f)
                                        .imageEngine(new GlideEngine())
                                        .forResult(REQUEST_CODE_CHOOSE);
                            }
                        })
                        .start();
            }
        });
        findViewById(R.id.layout_nick).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateUserInfoActivity.launcher(EditUserInfoActivity.this, 1,"");
            }
        });
        findViewById(R.id.layout_usercomment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateUserInfoActivity.launcher(EditUserInfoActivity.this,2,"");
            }
        });
        findViewById(R.id.layout_sex).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateUserInfoActivity.launcher(EditUserInfoActivity.this,3,"");
            }
        });
        findViewById(R.id.layout_birthday).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateUserInfoActivity.launcher(EditUserInfoActivity.this,4,"");
            }
        });
        findViewById(R.id.layout_locality).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateUserInfoActivity.launcher(EditUserInfoActivity.this,5,"");
            }
        });
        findViewById(R.id.layout_school).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateUserInfoActivity.launcher(EditUserInfoActivity.this, 6,"");
            }
        });
    }

    Uri imageUri = Uri.fromFile(PictureSelectUtils.getCropTempPhoto());
    private void crop(Uri uri) {

        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这里加入flag
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", false);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_edit_userinfo;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            if (requestCode == 1) {
                showUserInfo();
            } else if (requestCode == REQUEST_CODE_CHOOSE) {
                List<Uri> uriList = Matisse.obtainResult(data);
                if (uriList != null && uriList.size() > 0) {
                    Uri uri = uriList.get(0);
                    File file = PictureSelectUtils.getFileWithUri(uri,EditUserInfoActivity.this);
                    if (file == null) {
                        ToastManager.getInstance().showToast("图片没找到");
                        return;
                    }
                    crop(uri);
                }

            } else if (requestCode == PHOTO_REQUEST_CUT) {
                File file = PictureSelectUtils.getFileWithUri(imageUri,EditUserInfoActivity.this);
                if (file == null) {
                    ToastManager.getInstance().showToast("图片没找到");
                    return;
                }
                ToastManager.getInstance().showToast("" + file.length() / 1024 /1024);
                Luban.with(this)
                        .load(file)
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {
                                ToastManager.getInstance().showToast("" + file.length() / 1024 /1024);
                                updateHeadPhoto(file);
                            }

                            @Override
                            public void onError(Throwable e) {
                                ToastManager.getInstance().showToast(e.getMessage());
                            }
                        })
                        .launch();
            }
        }
    }

    private void showUserInfo() {
        UserInfo info = UserToken.getDefault().getUser();
        Glide.with(this).load(info.getUserLogo()).into(iv_userLogo);
        tv_userNick.setText(info.getNickName() == null ? "" : info.getNickName());
        tv_userComment.setText(info.getUserComment() == null ? "" : info.getUserComment());
        String sex = "";
        if (info.getSex() == 1) {
            sex = "男";
        } else if (info.getSex() == 2) {
            sex = "女";
        } else if (info.getSex() == 0) {
            sex = "不显示";
        }
        tv_userSex.setText(sex);
        tv_userBirthday.setText(info.getBirthday() == null ? "" : DateUtil.stampToDate(info.getBirthday(),"yyyy-MM-dd"));
        tv_userLocality.setText(info.getLocality() == null ? "" : info.getLocality());
        tv_userSchool.setText(info.getSchoolName() == null ? "" : info.getSchoolName());

    }

    private void updateHeadPhoto(File file) {
        new UserModleImpl().editUserHead(UserToken.getDefault().getToken(), file, new DataCallBack<UserInfoWrap>() {
            @Override
            public void onGetData(UserInfoWrap data) {
                super.onGetData(data);
                if (data != null && data.getUserInfo() != null) {
                    ToastManager.getInstance().showToast("头像设置成功");
                    UserToken.getDefault().getUser().setImage(data.getUserInfo().getImage());
                    UserToken.getDefault().save();
                    showUserInfo();
                }
            }

            @Override
            public void onFail(int code, String errorMessage) {
                super.onFail(code, errorMessage);
                ToastManager.getInstance().showToast(errorMessage);
            }
        });
    }
}
